package com.oritsh.dicom.service;

import com.oritsh.dicom.exception.DicomException;
import com.oritsh.dicom.scu.FindSCU;
import com.oritsh.dicom.utils.SCUFactory;
import org.dcm4che.data.Attributes;
import org.dcm4che.data.Tag;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: zarra
 * Date: 14-2-5
 * Time: 下午6:35
 * Copyright Shanghai Orient Rain Information Technology Co.,Ltd.
 */

public class CFindService {

    SCUFactory scuFactory;

    CFindAttributesTemplate cFindAttributesTemplate;

    public SCUFactory getScuFactory() {
        return scuFactory;
    }

    public void setScuFactory(SCUFactory scuFactory) {
        this.scuFactory = scuFactory;
    }

    public CFindAttributesTemplate getcFindAttributesTemplate() {
        return cFindAttributesTemplate;
    }

    public void setcFindAttributesTemplate(CFindAttributesTemplate cFindAttributesTemplate) {
        this.cFindAttributesTemplate = cFindAttributesTemplate;
    }

    public Attributes[] rawFind(Attributes requestDataset)throws DicomException {
        try (FindSCU findSCU = scuFactory.findSCU()){
            return findSCU.find(requestDataset);
        }
    }

    public Attributes[] findDataSetByPatientID(String patientID) throws DicomException {
        Attributes attributes = cFindAttributesTemplate.templateForFindByPatientID(patientID);
        return rawFind(attributes);
    }

    public Attributes[] findDataSetByStudyDate(String studyDate) throws DicomException {
        Attributes attributes = cFindAttributesTemplate.templateForFindByStudyDate(studyDate);
        return rawFind(attributes);
    }


    public Attributes[] findDataSetByStudyUID(String pid,String studyUID) throws DicomException {
        Attributes attributes = cFindAttributesTemplate.templateForFindByStudyUID(pid,studyUID);
        return rawFind(attributes);
    }

    public Attributes[] findDataSetBySeriesUID(String studyUID,String seriesUID) throws DicomException {
        Attributes attributes = cFindAttributesTemplate.templateForFindBySeriesUID(studyUID,seriesUID);
        return rawFind(attributes);
    }

    public Attributes[] findAllImageByStudyUID(String pid,String studyUID)throws DicomException{
        List<Attributes> result = new ArrayList<>();
        Attributes[] attributes = findDataSetByStudyUID(pid,studyUID);
        for (Attributes a : attributes){
            String seriesUID = a.getString(Tag.SeriesInstanceUID);
            Attributes[] attributeses = findDataSetBySeriesUID(studyUID,seriesUID);
            result.addAll(Arrays.asList(attributeses));
        }
        return result.toArray(new Attributes[0]);
    }
}
